// 会员积分模块主脚本
let selectedMember = null;
let selectedProduct = null;
let exchangeProducts = [];

/**
 * 计算所需积分和兑换后剩余积分
 */
function updateRequiredAndAfter() {
    const quantity = parseInt(document.getElementById('redeem-qty').value) || 1;
    const currentPoints = parseInt(document.getElementById('current-points').value) || 0;
    
    if (selectedProduct) {
        // 使用持久化的所需积分或默认计算
        const perUnit = parseInt(selectedProduct.required_points) || Math.round(selectedProduct.price * 10);
        const requiredPoints = perUnit * quantity;
        document.getElementById('required-points').value = requiredPoints;
        
        // 计算兑换后剩余积分
        const afterPoints = currentPoints - requiredPoints;
        document.getElementById('after-points').value = afterPoints;
        
        // 如果积分不足，显示提示
        if (afterPoints < 0) {
            document.getElementById('after-points').style.color = 'red';
        } else {
            document.getElementById('after-points').style.color = '';
        }
    } else {
        document.getElementById('required-points').value = '';
        document.getElementById('after-points').value = '';
    }
}

/**
 * 初始化兑换表单
 */
function initRedeemForm() {
    const memberSearch = document.getElementById('member-search');
    const memberInfo = document.getElementById('member-info');
    const productSelect = document.getElementById('product-select');
    const redeemQty = document.getElementById('redeem-qty');
    const redeemForm = document.getElementById('redeem-form');
    
    // 加载可兑换商品
    fetch('/api/exchange-products')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                exchangeProducts = data.data;
                
                // 清空现有选项
                productSelect.innerHTML = '<option value="">请选择商品</option>';
                
                // 添加商品选项
                exchangeProducts.forEach(product => {
                    const option = document.createElement('option');
                    option.value = product.product_code;
                    option.textContent = `${product.product_name} (库存:${product.current_stock})`;
                    // 持久化所需积分
                    option.dataset.points = product.required_points || Math.round(product.price * 10);
                    productSelect.appendChild(option);
                });
            }
        })
        .catch(error => {
            console.error('加载兑换商品失败:', error);
            showNotification('加载兑换商品失败', 'error');
        });
    
    // 会员搜索
    memberSearch.addEventListener('input', function() {
        const searchValue = this.value.trim();
        if (searchValue.length >= 3) {
            // 如果输入是纯数字且长度在11位左右，认为是手机号
            const isPhone = /^\d{3,13}$/.test(searchValue);
            
            if (isPhone) {
                fetch(`/api/members/phone/${searchValue}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            selectedMember = data.data;
                            memberInfo.textContent = `${selectedMember.name} - 积分:${selectedMember.points}`;
                            document.getElementById('current-points').value = selectedMember.points;
                            updateRequiredAndAfter();
                            
                            // 加载积分记录
                            loadMemberPointRecords(selectedMember.member_code);
                        } else {
                            memberInfo.textContent = '未找到会员';
                            selectedMember = null;
                            document.getElementById('current-points').value = '';
                        }
                    })
                    .catch(error => {
                        console.error('查询会员失败:', error);
                        memberInfo.textContent = '查询失败';
                    });
            } else {
                // 如果不是手机号，这里可以实现按姓名搜索
                // 需要后端支持，简化版暂不实现
            }
        } else {
            memberInfo.textContent = '';
            selectedMember = null;
            document.getElementById('current-points').value = '';
        }
    });
    
    // 商品选择变更
    productSelect.addEventListener('change', function() {
        const productCode = this.value;
        selectedProduct = exchangeProducts.find(p => p.product_code === productCode);
        updateRequiredAndAfter();
    });
    
    // 数量变更
    redeemQty.addEventListener('input', function() {
        updateRequiredAndAfter();
    });
    
    // 提交兑换
    redeemForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        if (!selectedMember) {
            showNotification('请先选择会员', 'warning');
            return;
        }
        
        if (!selectedProduct) {
            showNotification('请选择兑换商品', 'warning');
            return;
        }
        
        const quantity = parseInt(redeemQty.value) || 1;
        const requiredPoints = parseInt(document.getElementById('required-points').value);
        
        if (selectedMember.points < requiredPoints) {
            showNotification('会员积分不足', 'error');
            return;
        }
        
        // 发送兑换请求
        fetch('/api/redeem', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                member_code: selectedMember.member_code,
                product_code: selectedProduct.product_code,
                quantity: quantity,
                points_cost: requiredPoints  // 将计算的积分消耗发送到后端
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('兑换成功', 'success');
                
                // 更新会员积分
                selectedMember = data.data.member;
                document.getElementById('current-points').value = selectedMember.points;
                memberInfo.textContent = `${selectedMember.name} - 积分:${selectedMember.points}`;
                
                // 更新积分记录表格
                if (data.data.recent_records) {
                    updatePointRecordsTable(data.data.recent_records);
                } else {
                    // 重新加载积分记录
                    loadMemberPointRecords(selectedMember.member_code);
                }
                
                // 重置表单
                productSelect.value = '';
                redeemQty.value = 1;
                selectedProduct = null;
                updateRequiredAndAfter();
            } else {
                showNotification(data.message || '兑换失败', 'error');
            }
        })
        .catch(error => {
            console.error('兑换请求失败:', error);
            showNotification('兑换请求失败', 'error');
        });
    });
}

/**
 * 初始化从库存添加商品的模态框
 */
function initProductSelectModal() {
    const addRedeemProductBtn = document.getElementById('add-redeem-product-btn');
    const redeemModal = document.getElementById('redeem-modal');
    const redeemModalList = document.getElementById('redeem-modal-list');
    const redeemModalCancel = document.getElementById('redeem-modal-cancel');
    const redeemModalConfirm = document.getElementById('redeem-modal-confirm');
    
    // 创建商品表格
    function createProductTable(products) {
        const table = document.createElement('table');
        table.className = 'data-table';
        
        // 创建表头
        const thead = document.createElement('thead');
        const headerRow = document.createElement('tr');
        ['选择', '商品编码', '商品名称', '分类', '价格', '当前库存'].forEach(text => {
            const th = document.createElement('th');
            th.textContent = text;
            headerRow.appendChild(th);
        });
        thead.appendChild(headerRow);
        table.appendChild(thead);
        
        // 创建表体
        const tbody = document.createElement('tbody');
        products.forEach(product => {
            const row = document.createElement('tr');
            
            // 选择框
            const selectCell = document.createElement('td');
            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.dataset.productCode = product.product_code;
            selectCell.appendChild(checkbox);
            row.appendChild(selectCell);
            
            // 商品信息
            ['product_code', 'product_name', 'category'].forEach(field => {
                const cell = document.createElement('td');
                cell.textContent = product[field];
                row.appendChild(cell);
            });
            
            // 价格
            const priceCell = document.createElement('td');
            priceCell.textContent = `¥${product.price.toFixed(2)}`;
            row.appendChild(priceCell);
            
            // 库存
            const stockCell = document.createElement('td');
            stockCell.textContent = product.current_stock;
            row.appendChild(stockCell);
            
            tbody.appendChild(row);
        });
        table.appendChild(tbody);
        
        return table;
    }
    
    // 点击添加商品按钮
    addRedeemProductBtn.addEventListener('click', function() {
        // 加载库存商品
        fetch('/api/inventory-products')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 清空模态框内容
                    redeemModalList.innerHTML = '';
                    
                    // 只显示有库存的商品
                    const availableProducts = data.data.filter(product => product.current_stock > 0);
                    
                    if (availableProducts.length > 0) {
                        // 添加商品表格
                        const table = createProductTable(availableProducts);
                        redeemModalList.appendChild(table);
                    } else {
                        redeemModalList.innerHTML = '<p>没有可用的库存商品</p>';
                    }
                    
                    // 显示模态框
                    redeemModal.style.display = 'flex';
                } else {
                    showNotification(data.message || '加载库存商品失败', 'error');
                }
            })
            .catch(error => {
                console.error('加载库存商品失败:', error);
                showNotification('加载库存商品失败', 'error');
            });
    });
    
    // 取消按钮
    redeemModalCancel.addEventListener('click', function() {
        redeemModal.style.display = 'none';
    });
    
    // 确认按钮
    redeemModalConfirm.addEventListener('click', function() {
        // 获取选中的商品
        const selectedCheckboxes = redeemModalList.querySelectorAll('input[type="checkbox"]:checked');
        const selectedCodes = Array.from(selectedCheckboxes).map(cb => cb.dataset.productCode);
        
        if (selectedCodes.length === 0) {
            showNotification('请至少选择一种商品', 'warning');
            return;
        }
        
        // 持久化选择的兑换商品
        fetch('/api/exchange-products', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ product_codes: selectedCodes })
        })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                showNotification(result.message || '添加兑换商品成功', 'success');
                // 关闭模态框
                redeemModal.style.display = 'none';
                // 重新加载持久化的兑换商品列表
                fetch('/api/exchange-products')
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) {
                            exchangeProducts = data.data;
                            const productSelect = document.getElementById('product-select');
                            productSelect.innerHTML = '<option value="">请选择商品</option>';
                            exchangeProducts.forEach(product => {
                                const option = document.createElement('option');
                                option.value = product.product_code;
                                option.textContent = `${product.product_name} (库存:${product.current_stock})`;
                                // 持久化所需积分
                                option.dataset.points = product.required_points || Math.round(product.price * 10);
                                productSelect.appendChild(option);
                            });
                        }
                    });
            } else {
                showNotification(result.message || '添加兑换商品失败', 'error');
            }
        })
        .catch(error => {
            console.error('添加兑换商品失败:', error);
            showNotification('添加兑换商品失败', 'error');
        });
    });
}

/**
 * 加载会员积分记录
 */
function loadMemberPointRecords(memberCode) {
    fetch(`/api/members/${memberCode}/point-records`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updatePointRecordsTable(data.data);
            } else {
                console.error('加载积分记录失败:', data.message);
            }
        })
        .catch(error => {
            console.error('加载积分记录失败:', error);
        });
}

/**
 * 加载最近的积分记录（不指定会员）
 */
function loadRecentPointRecords() {
    // 调用API获取最近的积分记录
    fetch('/api/point-records/recent')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data && data.data.length > 0) {
                updatePointRecordsTable(data.data);
                updatePointsStatistics(data.statistics);
            } else {
                console.log('API未返回积分记录或记录为空');
                // 在API未返回数据时显示空表格
                showEmptyPointRecords();
                
                // 尝试更新统计数据
                if (data.success && data.statistics) {
                    updatePointsStatistics(data.statistics);
                }
            }
        })
        .catch(error => {
            console.error('加载最近积分记录失败:', error);
            // 在错误情况下显示空表格
            showEmptyPointRecords();
        });
}

/**
 * 显示空的积分记录表格
 */
function showEmptyPointRecords() {
    const tableBody = document.querySelector('.data-table tbody');
    if (!tableBody) return;
    
    // 清空表格
    tableBody.innerHTML = '';
    
    // 添加一行空记录提示
    const emptyRow = document.createElement('tr');
    const emptyCell = document.createElement('td');
    emptyCell.colSpan = 4;
    emptyCell.textContent = '请先输入会员信息';
    emptyCell.style.textAlign = 'center';
    emptyCell.style.padding = '20px';
    emptyCell.style.color = '#94a3b8';
    emptyRow.appendChild(emptyCell);
    tableBody.appendChild(emptyRow);
}

/**
 * 更新积分统计数据
 */
function updatePointsStatistics(stats) {
    if (!stats) return;
    
    // 更新统计卡片
    const statElements = document.querySelectorAll('.stat-content span:first-child');
    
    if (statElements.length >= 3) {
        // 总发放积分
        if (stats.total_earned) {
            statElements[0].textContent = formatNumber(stats.total_earned);
        }
        
        // 今日发放积分
        if (stats.today_earned) {
            statElements[1].textContent = formatNumber(stats.today_earned);
        }
        
        // 今日使用积分
        if (stats.today_used) {
            statElements[2].textContent = formatNumber(stats.today_used);
        }
    }
}

/**
 * 格式化数字（添加千位分隔符）
 */
function formatNumber(num) {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

/**
 * 更新积分记录表格
 */
function updatePointRecordsTable(records) {
    const tableBody = document.querySelector('.data-table tbody');
    if (!tableBody) return;
    
    // 清空表格
    tableBody.innerHTML = '';
    
    // 添加记录
    if (records && records.length > 0) {
        records.forEach(record => {
            const row = document.createElement('tr');
            
            // 时间列
            const timeCell = document.createElement('td');
            timeCell.textContent = record.create_time;
            row.appendChild(timeCell);
            
            // 会员信息列
            const memberCell = document.createElement('td');
            if (record.member_name && record.member_code) {
                memberCell.textContent = `${record.member_name} (${record.member_code})`;
            } else if (record.member_name) {
                memberCell.textContent = record.member_name;
            } else if (record.member_code) {
                memberCell.textContent = record.member_code;
            } else {
                memberCell.textContent = '未知会员';
            }
            row.appendChild(memberCell);
            
            // 积分变动列
            const pointsCell = document.createElement('td');
            if (record.record_type === 'earn') {
                pointsCell.textContent = `+${record.points}`;
                pointsCell.style.color = '#22c55e';
                pointsCell.style.fontWeight = '500';
            } else {
                pointsCell.textContent = `-${record.points}`;
                pointsCell.style.color = '#ef4444';
                pointsCell.style.fontWeight = '500';
            }
            row.appendChild(pointsCell);
            
            // 剩余积分列
            const balanceCell = document.createElement('td');
            if (record.remaining_points !== undefined) {
                balanceCell.textContent = record.remaining_points;
            }
            row.appendChild(balanceCell);
            
            // 将行添加到表格
            tableBody.appendChild(row);
        });
    } else {
        // 没有记录时显示空表格提示
        showEmptyPointRecords();
    }
}

/**
 * 通知函数
 */
function showNotification(message, type = 'info') {
    // 检查是否已经定义了这个函数
    if (typeof window.showNotification === 'function') {
        window.showNotification(message, type);
    } else {
        // 简单的fallback实现
        alert(message);
    }
}

/**
 * 初始化会员积分模块
 */
function initMemberPointsModule() {
    // 初始化表单处理
    initRedeemForm();
    
    // 初始化模态框
    initProductSelectModal();
    
    // 加载基础统计数据和最近的积分记录
    fetch('/api/sales/stats')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 可以使用销售统计数据更新积分统计卡片
                // 简化版暂不实现
            }
        })
        .catch(error => {
            console.error('加载销售统计数据失败:', error);
        });
    
    // 立即加载最近的积分记录
    loadRecentPointRecords();
    
    // 设置定时刷新最近积分记录（每60秒刷新一次）
    setInterval(loadRecentPointRecords, 60000);
}

// 页面加载完成后初始化模块
document.addEventListener('DOMContentLoaded', function() {
    initMemberPointsModule();
}); 